import { keywordCompare } from '@gnlab/utils'
import { Button, AutoComplete, message } from 'antd'
import type { DefaultOptionType } from 'antd/es/select'
import { EditModal } from '@/desktop/components'
import { useStreams } from '@/lib/utils'
import services from '@/services'
import type { GroupTag } from '@/services/contact-types/groups'
import './index.module.less'

/**
 * 创建或选中一个标签，若不传 choosable 则只提供创建标签功能
 */
export default function AddOrChooseGroupTagModal(props: {
  adding: boolean
  choosable?: boolean
  choosed?: GroupTag[]
  initialInput?: string
  onFinish: (tag?: GroupTag) => void
}) {
  const { adding, initialInput, choosable, choosed, onFinish } = props

  return <EditModal title="新建群标签" width="600px" open={adding} onCancel={() => onFinish()}>
    {adding ? (
      <Content
        onFinish={onFinish}
        choosable={choosable}
        choosed={choosed}
        initialInput={initialInput}
      />
    ) : null}
  </EditModal>
}

function Content(props: {
  choosable?: boolean
  choosed?: GroupTag[] // 已被选择的标签，此列表内的标签不可再次选择（仅 choosable=true 时生效）
  initialInput?: string
  onFinish: (tag?: GroupTag) => void // 若是“取消”，则触发回调时不会传 tag。若 choosable 为 true，此处传回的 tag 可能是之前就已存在的。
}) {
  const { choosable = false, choosed = [], initialInput = '', onFinish } = props

  const [allTags] = useStreams(services.groups.tags)
  useEffect(() => {
    void services.groups.loadTags()
  }, [])

  const [value, setValue] = useState(initialInput)

  const [submitting, setSubmitting] = useState(false)
  const submit = useCallback(async () => {
    const name = value.trim()

    const existTag = allTags.find(tag => tag.name === name)
    if (existTag) {
      if (choosable) return void onFinish(existTag)
      return void message.warning('已存在同名标签，无法创建')
    }

    setSubmitting(true)
    const res = await services.groups.addTag(name)
    setSubmitting(false)
    if (res.success) onFinish(res.data)
    else void message.warning(`标签创建失败：${res.error}`)
  }, [value, choosable, allTags, onFinish])

  const options = useMemo(() => {
    return choosable
      ? allTags.map(tag =>
          !choosed.find(t => t.id === tag.id)
            ? { label: tag.name, value: tag.name }
            : { label: `${tag.name}（已选中）`, value: tag.name, disabled: true },
        )
      : allTags.map(tag => ({ label: tag.name, value: tag.name }))
  }, [choosable, choosed, allTags])

  const filterOption = useCallback((inputValue: string, option?: DefaultOptionType) => {
    return !!option && keywordCompare(inputValue.trim(), option.value as string)
  }, [])

  return <>
    <main styleName="main">
      <label>标签名：</label>
      <AutoComplete
        disabled={submitting}
        autoFocus
        placeholder="输入标签名"
        filterOption={filterOption}
        options={options}
        value={value}
        onChange={setValue}
        onKeyDown={e => {
          if ((e.key === 'Enter' || e.code === 'Enter') && value.trim()) void submit()
        }}
      />
    </main>
    <footer>
      <Button type="primary" disabled={!value.trim()} loading={submitting} onClick={submit}>
        确定
      </Button>
    </footer>
  </>
}
